<template>
  <el-card class="box-card">
    <!-- 搜索框 -->
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="姓名" class="movement">
          <el-input
            v-model="formInline.name"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" class="movement">
          <el-input
            v-model="formInline.phone_number"
            placeholder="请输入手机号"
            class="movement"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()" class="movement"
            >查询</el-button
          >
          <el-button type="primary" @click="reset()" class="movement"
            >重置</el-button
          >
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 列表展示 -->
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        max-height="600"
      >
        <el-table-column align="center" label="ID" prop="id" width="70">
        </el-table-column>
        <el-table-column prop="name" align="center" label="姓名">
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          prop="img"
          align="center"
          label="头像"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.img"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>

        <el-table-column prop="phone_number" align="center" label="手机号">
        </el-table-column>
        <el-table-column prop="position_name" align="center" label="职位">
        </el-table-column>
        <el-table-column
          prop="is_status"
          align="center"
          label="状态"
          :formatter="formatUserState"
        >
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.is_status === 1"
              type="danger"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >禁用</el-button
            >
            <el-button
              v-else
              type="primary"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >启用</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="deleteUser(scope.$index, scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              @click="compile(scope.$index, scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[50, 100, 200, 300]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 新增员工 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="handleClose"
    >
      <el-form
        :model="formLabelAlign"
        label-width="85px"
        ref="managementForm"
        :rules="rules"
      >
        <div class="oneLine">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              placeholder="请输入员工姓名"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="用户编码" prop="user_id">
            <el-input
              :disabled="disabled"
              v-model="formLabelAlign.user_id"
              placeholder="请输入员工编码"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="手机号" prop="region">
            <el-input
              v-model="formLabelAlign.region"
              placeholder="请输入员工手机号"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="职位" prop="type">
            <el-input v-model="formLabelAlign.type" :disabled="true"></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="头像" prop="imageUrl">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFiles"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
                :on-change="fileChange"
              >
                <el-image
                  v-if="imageUrl"
                  class="imageGood"
                  :src="imageUrl"
                  style="width: 360px; height: 180px"
                ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div>
        <el-button
          type="primary"
          dialogVisible
          class="confirm"
          @click="submitData('managementForm')"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  user_po_list,
  uploadFiles,
  employee,
  condition,
  userDelete,
  compileAuth,
} from "../../../../utils/api";
import { compressImage } from "../../../../assets/js/compressImage";
export default {
  data() {
    return {
      loading: false,
      token: sessionStorage.getItem("token"),
      formInline: {
        name: "",
        phone_number: "",
      },
      //新增员工弹框
      disabled: false,
      dialogVisible: false,
      currentPage: 1,
      total: 0,
      limit: 10,
      page: 1,
      authority_id: 5,
      tableData: [
        {
          id: "",
          user_id: "",
          name: "",
          phone_number: "",
          identity_img1: "",
          identity_img2: "",
          authority_id: "",
          position_name: "",
          is_status: "",
          names: "",
          img: "",
          image: "",
          is_baiben: "",
          jiguan: "",
          gonling: "",
          user_skill: "",
        },
      ],
      //新增员工
      formLabelAlign: {
        name: "",
        region: "",
        type: "送水工",
        user_id: "",
      },
      //上传图片
      imageUrl: "",
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      imgHeader: this.Global.imgHeader,

      //校验
      rules: {
        name: [
          { required: true, message: "请输入员工姓名", trigger: "change" },
        ],
        user_id: [
          { required: true, message: "请输入员工编码", trigger: "change" },
        ],
        region: [
          { required: true, message: "请输入工手机号", trigger: "change" },
          {
            validator: function (rule, value, callback) {
              if (/^1[3456789]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        type: [
          { required: true, message: "请输入员工职位", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    //新增员工的数据
    clearData() {
      this.$refs.managementForm.resetFields();
      this.formLabelAlign.name = "";
      this.formLabelAlign.region = "";
      this.formLabelAlign.user_id = "";
      this.imageUrl = "";
    },
    //关闭弹框
    handleClose(done) {
      done();
      this.clearData();
    },
    //查询
    searchUser() {
      this.loading = true;
      user_po_list(
        this.token,
        this.page,
        this.formInline.name,
        this.formInline.phone_number,
        this.limit,
        this.authority_id
      )
        .then((res) => {
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.count;
            this.tableData.forEach((item) => {
              if (item.img) {
                item.image = item.img;
                item.img = this.imgHeader + item.img;
                console.log(item.img);
              }
            });

            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.msg);
        });
    },
    search() {
      this.page = 1;
      this.searchUser();
    },
    reset() {
      (this.formInline.name = ""), (this.formInline.phone_number = "");
      this.searchUser();
    },
    //分页器
    //每页多少条
    handleSizeChange(val) {
      this.limit = val;
      this.searchUser();
    },
    //第几页
    handleCurrentChange(val) {
      this.page = val;
      this.searchUser();
    },

    // 序号排序
    indexMethod(index) {
      if (this.token < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.currentPage - 1) * this.limit - index;
      }
    },

    //状态值
    conditionUser(id, status) {
      condition(this.token, id, status)
        .then((res) => {
          if (res.data.status) {
            this.searchUser();
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //启用
    handleEdit(index, row) {
      if (row.is_status === 0) {
        let is_status = 1;
        this.conditionUser(row.id, is_status);
      }
      if (row.is_status === 1) {
        let is_status = 2;
        this.conditionUser(row.id, is_status);
      }
      if (row.is_status === 2) {
        let is_status = 1;
        this.conditionUser(row.id, is_status);
      }
      this.searchUser;
    },
    //删除
    deleteUser(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.is_status == 2) {
            userDelete(this.token, row.id).then((res) => {
              if (res.data.status) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.search();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            this.$message({
              type: "warning",
              message: "员工在职,无法删除",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true;
      this.disabled = false;
    },
    //编辑
    compile(index, row) {
      this.disabled = true;
      if (row.is_status == 2) {
        let obj = JSON.parse(JSON.stringify(row));
        console.log(obj);
        this.formLabelAlign.name = obj.name;
        this.formLabelAlign.region = obj.phone_number;
        this.formLabelAlign.type = obj.position_name;
        this.formLabelAlign.user_id = obj.user_id;
        this.imageUrl = row.img;
        this.tableData.id = obj.id;
        this.dialogVisible = true;
      } else {
        this.$message({
          type: "warning",
          message: "员工在职,无法进行编辑",
        });
      }
    },
    //新增员工
    handleRemove() {},
    //添加员工
    save() {
      employee(
        this.token,
        this.imageUrl1,
        this.formLabelAlign.region,
        this.formLabelAlign.name,
        this.formLabelAlign.user_id,
        this.authority_id
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.clearData();
          this.searchUser();
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
            let timer = setTimeout(() => {
              this.$message.error("错误，请刷新");
            }, 5000);
          }
          this.$message.error(res.data.msg);
        }
      });
    },

    //确定添加员工的回调
    submitData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.tableData.id) {
            compileAuth(
              this.token,
              this.imageUrl1,
              this.formLabelAlign.region,
              this.formLabelAlign.name,
              this.formLabelAlign.user_id,
              this.authority_id,
              this.tableData.id
            ).then((res) => {
              console.log(res);
              if (res.data.status) {
                this.$message({
                  message: "修改成功",
                  type: "success",

                  onClose: (res) => {},
                });
                this.search();
                this.dialogVisible = false;
                this.clearData();
                this.$refs[formName].resetFields();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            this.dialogVisible = false;
            this.save();
            this.clearData();
          }
        }
      });
    },

    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //这是我自定义的移除事件
    handleClosedelete(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFiles(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.imageUrl = res.data.data.weburl;
            this.imageUrl1 = res.data.data.saveurl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFiles(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     console.log(res);
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.imageUrl1 = res.data.data.saveurl;
      //     this.imageUrl = res.data.data.weburl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },
    formatUserState(row) {
      let is_status = row.is_status;
      if (is_status === 1) {
        return "在职";
      } else if (is_status === 2) {
        return "离职";
      } else {
        return "未审核";
      }
    },
  },
  mounted() {
    // this.toAdd();
    this.search();
  },
};
</script>

<style scoped>
.confirm {
  margin-left: 40%;
}

.movement {
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}
</style>